package com.travel.server.manager.impl.dal;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dao.ArticleClassInfoDao;
import com.travel.server.manager.model.ArticleClassInfo;
import com.travel.server.manager.model.ArticleClassInfoExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/20 15:00
 * @Desc:
 */
@Component
@Slf4j
public class ArticleClassDal {

    @Autowired
    private ArticleClassInfoDao dao;

    public PageDto<ArticleClassInfo> selectByPage(Integer offset, Integer limit){
        ArticleClassInfoExample example = new ArticleClassInfoExample();
        ArticleClassInfoExample.Criteria criteria = example.or();
        criteria.andStateEqualTo(CommonConstant.YES);
        Integer total = dao.countByExample(example);
        example.setOffset(offset);
        example.setLimit(limit);
        example.setOrderByClause("update_time desc");
        List<ArticleClassInfo> list = dao.selectByExample(example);
        return new PageDto<>(list, total);
    }

    public ArticleClassInfo selectById(Integer id){
        ArticleClassInfo info = dao.selectByPrimaryKey(id);
        if(info == null){
            log.info("not find ArticleClassInfo, id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return info;
    }

    public void insertOrUpdate(ArticleClassInfo articleClassInfo){
        if(articleClassInfo.getId() == null){
            dao.insertSelective(articleClassInfo);
        }else{
            dao.updateByPrimaryKey(articleClassInfo);
        }
    }

    public Map<Integer, String> makeMap(List<Integer> classIdList){
        ArticleClassInfoExample example = new ArticleClassInfoExample();
        ArticleClassInfoExample.Criteria criteria = example.or();
        criteria.andStateEqualTo(CommonConstant.YES);
        criteria.andIdIn(classIdList);
        List<ArticleClassInfo> list = dao.selectByExample(example);
        Map<Integer, String> map = new HashMap<>();
        if(!CollectionUtil.isEmpty(list)){
            for(ArticleClassInfo info : list){
                map.put(info.getId(), info.getClassName());
            }
        }
        return map;

    }
}
